package com.hwl.acl.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.hwl.acl.pojo.Role;
import com.hwl.acl.pojo.User;
import com.hwl.acl.service.IndexService;
import com.hwl.acl.service.PermissionService;
import com.hwl.acl.service.RoleService;
import com.hwl.acl.service.UserService;
import com.hwl.commonutils.exception.GuliException;
import com.hwl.commonutils.result.ResultCodeEnum;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class IndexServiceImpl implements IndexService {

    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;
    @Resource
    private PermissionService permissionService;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public Map<String, Object> getUserInfo(String username) {
        Map<String, Object> map = new HashMap<>();

        User user = userService.getUserByName(username);
        if (null == user || user.getIsDeleted()) {
            throw new GuliException(ResultCodeEnum.FETCH_USERINFO_ERROR);
        }

        //获取用户拥有的角色名
        List<String> roleNames = roleService.selectRoleByUserId(user.getId())
                .stream().map(Role::getRoleName).collect(Collectors.toList());
        if (roleNames.isEmpty()) {
            //如果没有角色，返回一个空角色，前端框架必须返回一个角色，否则报错
            roleNames.add("");
        }

        //根据用户id获取操作权限值
        List<String> permissionValueList = ((List<String>) redisTemplate.opsForValue().get(username));

        map.put("name", user.getUsername());
        map.put("avatar", "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        map.put("roles", roleNames);
        map.put("permissionValueList", permissionValueList);
        return map;
    }

    @Override
    public List<JSONObject> getMenu(String username) {
        User user = userService.getUserByName(username);
        if (null == user || user.getIsDeleted()) {
            throw new GuliException(ResultCodeEnum.FETCH_USERINFO_ERROR);
        }
        return permissionService.selectPermissionByUserId(user.getId());
    }
}
